package com.chookss.home.running;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.RunningActivityEntity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.BottomListsDialog;
import com.chookss.view.SelectDialogListener;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

public class RunningActivityActivity extends BaseAct {
//活动列表

    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.common_right_iv_ll)
    LinearLayout common_right_iv_ll;
    @BindView(R.id.common_right_iv)
    ImageView common_right_iv;
    @BindView(R.id.rvView)
    RecyclerView recyclerView;
    @BindView(R.id.srlView)
    SmartRefreshLayout smrRf;
    private RunningActivityAdapter adapter;
    private List<RunningActivityEntity> list = new ArrayList<>();
    private int currentPage = 1;
    private int pageSize = 20;
    private boolean isEnd = false;//是否到底
    private View emptyView;
    private TextView tvNone;//空布局;
    private String code = "";//登陆者code
    private BottomListsDialog bottomListsDialog = null;
    private List<String> dialogList = new ArrayList<>();
    private int searchType=1;//（1-查询我的 2-查询全部）

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.common_srlview_top);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        common_right_iv_ll.setVisibility(View.VISIBLE);
        LinearLayout.LayoutParams ivParams = (LinearLayout.LayoutParams) common_right_iv.getLayoutParams();
        ivParams.height = Utils.dip2px(this, (float) 5.5);
        ivParams.width = Utils.dip2px(this,23 );
        common_right_iv.setLayoutParams(ivParams);
        common_right_iv.setBackgroundResource(R.drawable.icon_more_23);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) smrRf.getLayoutParams();
        params.setMargins(0, Utils.dip2px(this, 19), 0, 0);
        smrRf.setLayoutParams(params);
        code = new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, "");
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new RunningActivityAdapter(R.layout.item_running_activity, this, list);
        recyclerView.getItemAnimator().setChangeDuration(0);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        recyclerView.setAdapter(adapter);
        emptyView = LayoutInflater.from(this).inflate(R.layout.layout_common_empty, recyclerView, false);
        tvNone = emptyView.findViewById(R.id.tvEmpty);
        commonTitleTxt.setText("活动列表");
        tvNone.setText("暂无活动记录");
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                getData();
            }
        });
        smrRf.autoRefresh();

    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        map.put("searchType", searchType + "");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<RunningActivityEntity>>>() {
        }.getType(), null, Urls.selectMoveInfoList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<RunningActivityEntity>>() {
            @Override
            public void onSuccess(List<RunningActivityEntity> data) {

                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (smrRf == null) {
                    return;
                }
                int old = list.size();
                if (data != null && data.size() > 0) {
                    if (data.size() < pageSize) {
                        isEnd = true;
                    }
                    list.addAll(data);
                    adapter.notifyItemRangeChanged(old, data.size());
                    smrRf.setVisibility(View.VISIBLE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        adapter.setEmptyView(emptyView);
                    } else {
                        adapter.notifyDataSetChanged();
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    class RunningActivityAdapter extends BaseQuickAdapter<RunningActivityEntity, BaseViewHolderEx> {
        private Activity context;

        public RunningActivityAdapter(int layoutResId, Activity context, @io.reactivex.annotations.Nullable List<RunningActivityEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, RunningActivityEntity entity) {
            TextView tvType1 = helper.getView(R.id.tvType1);
            TextView tvType2 = helper.getView(R.id.tvType2);
            TextView tvType3 = helper.getView(R.id.tvType3);
            TextView tvTitle = helper.getView(R.id.tvTitle);
            TextView tvPeople = helper.getView(R.id.tvPeople);
            ImageView ivBg = helper.getView(R.id.ivBg);
            LinearLayout morell = helper.getView(R.id.morell);
            GlideUtils.loadCustomRound2(context, entity.getImageUrl(), ivBg, 6);
            tvTitle.setText(entity.getActivityName());
            tvPeople.setText(entity.getEmpNum() + "人参与");
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tvTitle.getLayoutParams();
            params.setMargins(Utils.dip2px(context, 14), Utils.dip2px(context, 11), Utils.dip2px(context, 8), Utils.dip2px(context, 11));
            morell.setVisibility(View.VISIBLE);
            //statusCd 1未开始2进行中3已结束
            if(Utils.isNull(entity.getStatusCd())){
                tvType1.setVisibility(View.GONE);
                tvType2.setVisibility(View.GONE);
                tvType3.setVisibility(View.GONE);
            }else{
                if(entity.getStatusCd().equals("1")){
                    tvType1.setVisibility(View.VISIBLE);
                    tvType2.setVisibility(View.GONE);
                    tvType3.setVisibility(View.GONE);
                }else if(entity.getStatusCd().equals("2")){
                    tvType1.setVisibility(View.GONE);
                    tvType2.setVisibility(View.VISIBLE);
                    tvType3.setVisibility(View.GONE);
                }else if(entity.getStatusCd().equals("3")){
                    tvType1.setVisibility(View.GONE);
                    tvType2.setVisibility(View.GONE);
                    tvType3.setVisibility(View.VISIBLE);
                }else{
                    tvType1.setVisibility(View.GONE);
                    tvType2.setVisibility(View.GONE);
                    tvType3.setVisibility(View.GONE);
                }
            }
            tvTitle.setLayoutParams(params);
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    if(entity.getStatusCd().equals("1")){
                        MyToast.show("活动暂未开始，敬请期待");
                        return;
                    }
                    Intent intent = new Intent(RunningActivityActivity.this, RunningRankActivity.class);
                    intent.putExtra("activityCode", entity.getActivityCode());
                    intent.putExtra("activityName", entity.getActivityName());
                    intent.putExtra("statusCd", entity.getStatusCd());
                    startActivity(intent);
                }
            });
            morell.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showBottomDialog(0, helper.getItemPosition(),entity.getActivityCode(),entity.getId());
                }
            });
        }
    }

    private void showBottomDialog(int type,int index, String activityCode,String id) {
        dialogList.clear();
        if (type == 0) {
            //列表
            if (code.equals(list.get(index).getCreateEmployeeCode())) {
                dialogList.add("查看");
                dialogList.add("修改");
                dialogList.add("删除");
                dialogList.add("取消");
            } else {
                dialogList.add("查看");
                dialogList.add("取消");
            }
        } else {
            //右上角更多
            dialogList.add("新建活动");
            dialogList.add("查看全部");
            dialogList.add("只看我的");
            dialogList.add("取消");
        }
        bottomListsDialog = new BottomListsDialog(this, dialogList, new SelectDialogListener() {
            @Override
            public void onCancel() {

            }

            @Override
            public void onListItemClick(int position, List<String> lists) {

                if (type==0) {
                    //全部
                    if (position == 0) {
                        Intent intent = new Intent(RunningActivityActivity.this, RunningAddActivity.class);
                        intent.putExtra("activityCode", activityCode);
                        intent.putExtra("id", id);
                        intent.putExtra("isDetail", true);
                        startActivity(intent);
                    }
                    if (code.equals(list.get(index).getCreateEmployeeCode())) {
                        if (position == 1) {
                            if(list.get(index).getStatusCd().equals("3")){
                                MyToast.show("活动已结束，不支持修改");
                                return;
                            }
                            Intent intent = new Intent(RunningActivityActivity.this, RunningAddActivity.class);
                            intent.putExtra("activityCode", activityCode);
                            intent.putExtra("id", id);
                            startActivity(intent);
                        } else if (position == 2) {
                            deleteDialog(index,activityCode);
                        }
                    }

                } else {
                    if (position == 0) {
                        Intent intent = new Intent(RunningActivityActivity.this, RunningAddActivity.class);
                        startActivity(intent);
                    }else if (position ==1) {
                        searchType=2;
                        smrRf.autoRefresh();
                    }else if (position == 2) {
                        searchType=1;
                        smrRf.autoRefresh();
                    }
                }

                bottomListsDialog.dismiss();
            }
        });
        bottomListsDialog.show();
    }
    private void deleteDialog(int position,String activityCode) {
        new AlertDialog.Builder(this)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        deleteData(position,activityCode);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setMessage("确定要删除么?")
                .setTitle("提示")
                .show();
    }
    private void deleteData(int position,String activityCode) {
        Map<String, String> map = new HashMap<>();
        map.put("activityCode", activityCode);
        showLoading();
        MyHttpRequest.getDefault().postRequestCompat(null, Urls.deleteMoveInfo, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                JSONObject reObject = null;
                dismissLoading();
                try {
                    reObject = new JSONObject(data);
                    if ("200".equals(reObject.getString("code"))) {
                        MyToast.show("删除成功");
                        list.remove(position);
                        adapter.notifyItemRemoved(position);
                        adapter.notifyItemRangeChanged(position, list.size() - position);
                    } else {
                        MyToast.show(reObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(errorMsg);
            }
        });
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("RunningAddActivity_Publish")) {
                smrRf.autoRefresh();
            }
        }
    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    @OnClick({R.id.common_title_back, R.id.common_right_iv_ll})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.common_right_iv_ll:
                showBottomDialog(1,0 ,"","");
                break;
        }
    }
}
